<template>
  <div class="project-list">
    <a-list
      :bordered="false"
      :dataSource="projectList"
      :locale="{ emptyText: '暂无数据' }"
    >
      <template #header>
        <div class="list-header">
          <span class="taskHeadline">应用列表</span>
          <a-button size="small" type="primary" @click="toAdd">
            <template #icon><PlusOutlined /> </template>
          </a-button>
        </div>
      </template>
      <template #renderItem="{ item }">
        <a-list-item :class="item.id === projectId ? 'checkItem' : 'unCheckItem'"
            @click="changeProject(item)">
          <img
            class="icon-img"
            :src="getProjectIcon(item.type)"
          />
          <template #actions>
            <a-popover placement="rightBottom">
              <template #content>
                <p class="appBtn">
                  <CopyOutlined></CopyOutlined>
                  <a-button
                    size="small"
                    @click="toCopy(item)"
                    style="border-color: transparent"
                  >
                    拷贝
                  </a-button>
                </p>
                <p class="appBtn">
                  <DeleteOutlined></DeleteOutlined>
                  <a-button
                    size="small"
                    @click="remove(item)"
                    style="margin: 0; border-color: transparent"
                  >
                    删除
                  </a-button>
                </p>
              </template>
              <div class="dot">...</div>
            </a-popover>
          </template>
          <a-list-item-meta
            :description="item.name"
          ></a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
    <a-modal
      title="新增项目"
      v-model:visible="state.addVisible"
      width="35%"
      cancelText="取消"
      okText="确认"
      :maskClosable="false"
      :onOk="add"
    >
      <div class="addProjectContainer">
        <a-form ref="formRef" :rules="state.rules" :model="state.addForm">
          <a-form-item
            label="git 地 址 "
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
            name="gitUrl"
            :rules="[{ required: true, message: '请输入git地址!' }, { message: '请输入正确的git地址', pattern: /^git@[\w.-]+:[\w-/]+.git$/ }]"
          >
            <a-input style="margin-left: 10px;" v-model:value="state.addForm.gitUrl">
              <template #addonBefore>
                <a-select defaultValue="SSH" style="width: 70px">
                  <a-select-option value="SSH">SSH</a-select-option>
                </a-select>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            label="语言类型 "
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            class="new"
            name="type"
          >
            <a-select style="width: 241px;margin-left: 10px;" v-model:value="state.addForm.type">
              <a-select-option value="java">java</a-select-option>
              <a-select-option value="js">js</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal
      title="复制应用"
      v-model:visible="state.copyProjectVisible"
      width="40%"
      :maskClosable="false"
      :onOk="copy"
    >
      <div>环境：</div>
      <a-select
        v-model:value="state.copyForm.envId"
        style="border-color: transparent"
        :options="state.copyEnvList"
      ></a-select>
    </a-modal>
  </div>
</template>



<script lang="ts">
import { defineComponent, toRefs, reactive, ref } from "vue";
import { projectApi } from "@/api/devcloudApi";
import {
  PlusOutlined,
  CopyOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import { FormInstance, message } from "ant-design-vue";
import type { Rule } from "ant-design-vue/es/form";
import store from "@/store";

export default defineComponent({
  name: "projectList",
  props: {
    projectList: {
      type: Array,
      required: true,
    },
    productId: {
      type: Number,
      required: true,
    },
    projectId: {
      type: Number,
      required: false,
    },
  },
  emits: ["reload", "reloadModuleList"],
  components: {
    PlusOutlined,
    CopyOutlined,
    DeleteOutlined,
  },
  setup(props, ctx) {
    const formRef = ref<FormInstance>();
    const productId = props.productId;

    const gitUrlValidator = async (rule: Rule, value: string) => {
      if (!value.startsWith("git@")) {
        return Promise.reject("请输入ssh连接地址");
      }
      return Promise.resolve();
    }

    const state:any = reactive({
      addForm: {},
      addVisible: false,
      copyProjectVisible: false,
      rules: {
        gitUrl: [
          {
            required: true,
            validator: gitUrlValidator,
            validateTrigger: "onBlur",
            message: "请输入项目地址",
          },
        ],
        type: [{ required: true, message: "请选择语言类型" }],
      },
      copyForm: {
        id: '',
        envId: ''
      },
      copyEnvList: [{
        label: '',
        valie: ''
      }],
    });
    state.copyEnvList = []

    const initAddForm = () => {
      state.addForm = {
        productId: productId,
        envId: store.getters.getCurrInfo.envId,
      }
    }

    const toAdd = () => {
      initAddForm();
      state.addVisible = true;
    }

    const add = () => {
      formRef.value
        ?.validateFields()
        .then(async (item) => {
          const res = await projectApi.insert(state.addForm);
          if (res.success) {
            state.addVisible = false;
            store.commit('setCurrInfo', {'projectId': res.result.id, 'moduleId': ''})
            ctx.emit("reload", res.result.id);
            message.info("创建成功");
          }
        })
        .catch((e) => {
          console.log(e);
        });
    }

    const initCopyForm = (item: any) => {
      state.copyForm.id = item.id
    }

    const toCopy = async (item: any) => {
      const res = await projectApi.copyEnableEnv(item.name);
      if (res.success) {
        initCopyForm(item)
        state.copyEnvList = []
        res.result.forEach((el: any) => {
          state.copyEnvList.push({
            label: el.env,
            value: el.id
          })
        });
        state.copyProjectVisible = true;
      }
    }

    const copy = async () => {
      const res = await projectApi.copy(state.copyForm);
      if (res.success) {
        state.copyProjectVisible = false;
        message.info("复制成功");
      }
    }

    const changeProject = (item: any) => {
      if(item.id === props.projectId){
        return
      }
      ctx.emit("reloadModuleList", item);
    }

    const remove = async (item: any) => {
      const res = await projectApi.delete(item.id);
      if (res.success) {
        store.commit('setCurrInfo', {'projectId': '', 'moduleId': ''})
        ctx.emit("reload", res.result.id);
        message.info("删除成功");
      }
    }

    const getProjectIcon = (type:string) => {
      switch (type) {
        case "java":
          return require("../../../static/java-icon.svg");
          break;
        case "js":
          return require("../../../static/js.svg");
          break;
      }
    }

    return {
      state,
      formRef,
      toAdd,
      toCopy,
      copy,
      add,
      changeProject,
      remove,
      getProjectIcon
    }
  },
});
</script>
<style lang="less" scoped>
.project-list {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 24px !important;
  }

  .ant-list-item {
    display: flex;
    text-align: start;
    padding: 15px 18px !important;
    border-bottom: 1px solid #f0f0f0 !important;
  }
  .checkItem {
    height:58px;
    cursor:pointer;
    background-color: hsla(0, 0, 87.8%, 0.5);
  }
  .unCheckItem {
    height:58px;
    cursor:pointer;
  }
  .appBtn > p {
    padding: 0 5px;
  }

  .dot {
    transform: rotate(90deg);
    margin-right: 5px;
    user-select: none;
  }
  .icon-img {
    width: 22px;
    margin-right: 10px;
  }
}
</style>
